import Vue from 'vue';
import VueRouter from 'vue-router';

import Home from '../views/Home/Home.vue';
import Company from '../views/Company/Company.vue';
import CompanyDetail from '../views/Company/CompanyDetail.vue';
import Discounts from '../views/Discounts/Discounts.vue';
import DiscountsDetail from '../views/Discounts/DiscountDetail.vue';
import Pedia from '../views/Pedia/Pedia.vue';
import QA from '../views/Q&A/Q&A.vue';
import Guarantee from '../views/Guarantee/Guarantee.vue';
import GuaranteeDetail from '../views/Guarantee/GuaranteeDetail.vue';
import EditGuarantee from '../views/EditGuarantee/EditGuarantee.vue';
import Crown from '../views/Crown.vue';
import BBS from '../views/BBS.vue';
import Report from '../views/Report/Report.vue';

import { getToken, removeToken } from '../utils/auth';
import store from '../store';

Vue.use(VueRouter);

const routes = [{
  path: '/',
  redirect: '/home'
}, {
  path: '/home',
  name: 'Home',
  component: Home,
}, {
  path: '/company',
  name: 'Company',
  component: Company,
  children: [{
    path: '/company',
    name: 'companyList',
    component: () => import('../views/Company/CompanyList.vue'),
  }, {
    path: '/company/:id',
    name: 'companyDetail',
    component: CompanyDetail,
  }]
}, {
  path: '/discounts',
  name: 'Discounts',
  component: Discounts,
  children: [{
    path: '/discounts',
    name: 'discountsList',
    component: () => import('../views/Discounts/DiscountsList.vue'),
  }, {
    path: '/discounts/:id',
    name: 'discountDetail',
    component: DiscountsDetail
  }]
}, {
  path: '/pedia',
  name: 'Pedia',
  component: Pedia
}, {
  path: '/qa',
  name: 'QA',
  component: QA,
}, {
  path: '/guarantee',
  name: 'Guarantee',
  component: Guarantee,
  children: [{
    path: '/guarantee',
    name: 'GuaranteeList',
    component: () => import('../views/Guarantee/GuaranteeList.vue')
  }, {
    path: '/guarantee/:id',
    name: 'GuaranteeDetail',
    component: GuaranteeDetail
  }]
}, {
  path: '/editGuarantee',
  name: 'EditGuarantee',
  component: EditGuarantee
}, {
  path: '/crown',
  name: 'Crown',
  component: Crown,
}, {
  path: '/bbs',
  name: 'BBS',
  component: BBS,
}, {
  path: '/report',
  name: 'Report',
  component: Report,
}, {
  path: '/usercenter',
  name: 'UserCenter',
  component: () => import('../views/UserInfo/index.vue')
}];

const router = new VueRouter({
  routes,
});

router.beforeEach(async (to, from, next) => {
  const hasToken = getToken();

  if (hasToken) {
    if (!store.state.userInfo) {
      if (!localStorage.userInfo) {
        removeToken();
        store.commit('SHOW_LOGIN', true);
        return;
      }
      store.commit('LOGIN_SUCCESS', JSON.parse(localStorage.userInfo));
    }
    next();
  } else {
    store.commit('SHOW_LOGIN', true);
  }
});

export default router;
